package com.example.springstudy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springstudy.dao.dto.UserListDto;
import com.example.springstudy.entity.User;
import com.example.springstudy.mapper.RoleMapper;
import com.example.springstudy.mapper.UserMapper;
import com.example.springstudy.service.UserService;
import com.example.springstudy.utils.DateUtils;
import com.example.springstudy.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserMapper userMapper;


    @Override
    public List<User> searchUser(int type, String key) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(type==0){
            queryWrapper.and(user->{
                user
                        .like(User::getNickName, key)
                        .like(User::getPhone, key)
                        .like(User::getEmail, key);
            });
        }
        if (type == 1) {
            queryWrapper.eq(User::getPhone, key);
        }
        return this.list(queryWrapper);
    }

    @Override
    public User getUser(int id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public UserListDto getUserList(int page, int size) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(User::getIsDeleted, 1);
        IPage<User> ipage = new Page<>(page, size);
        Long total = this.count(wrapper);
        return new UserListDto(total, this.list(ipage, wrapper), page, size);
    }

    @Transactional
    @Override
    public boolean addUser(User user) {
        Long sysUserId = SecurityUtils.getUserId();
        if(user.getId() == null || user.getId()==0){
            user.setCreateBy(sysUserId);
            user.setCreateTime(DateUtils.defaultDate());
        } else {
            user.setUpdateTime(DateUtils.defaultDate());
            user.setUpdateBy(sysUserId);
        }
        if(user.getPassword()!=null && !StrUtil.isEmpty(user.getPassword())){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        if(StrUtil.isEmpty(user.getBirth())){
            user.setBirth(null);
        }
        if(user.getRoleIds()!=null && !user.getRoleIds().isEmpty()){
            roleMapper.deleteUserRole(user.getId());
            roleMapper.addUserRole(user.getId(), user.getRoleIds());
        }

        return this.saveOrUpdate(user);
    }

    @Override
    public boolean updateUser(User user) {
        return this.addUser(user);
    }

    @Override
    public boolean deleteUser(int id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User user = this.getOne(queryWrapper.eq(User::getId, id));
        user.setIsDeleted(1);
        return this.updateUser(user);
    }

    @Override
    public boolean updatePassword(String password, Long userId) {
        password = new BCryptPasswordEncoder().encode(password);
        log.info("update_password:{}", password);
        return userMapper.updatePassword(password, userId);
    }

}
